package com.topit.show.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topit.show.core.util.DigestUtils;
import com.topit.show.wxapi.common.WxConstants;

public class SignUtil {
	
	private static final Logger log = LoggerFactory.getLogger(SignUtil.class);
	
	/**
	 * 生成签名
	 * 
	 * @param params
	 * @param sortParamsKey
	 * @return
	 */
	public static String getSign(Map<String, String> params) {
		// 参数排序
		List<String> paramsKey = new ArrayList<String>();
		paramsKey.addAll(params.keySet());
		List<String> sortParamsKey = sort(paramsKey);
		StringBuilder signStr = new StringBuilder();
		for (String key : sortParamsKey) {
			signStr.append(key).append("=").append(params.get(key)).append("&");
		}
		String sign = null;
		try {
			sign = DigestUtils.md5(signStr.append("key=").append(WxConstants.APIKEY).toString()).toUpperCase();
		} catch (IOException e) {
			log.error("MD5加密一场 e ＝ {}", e);
		}
		return sign;
	}

	/**
	 * 排序
	 * 
	 * @param list
	 * @return
	 */
	private static List<String> sort(List<String> list) {
		MyString mySs[] = new MyString[list.size()];// 创建自定义排序的数组
		for (int i = 0; i < list.size(); i++) {
			mySs[i] = new MyString(list.get(i));
		}
		Arrays.sort(mySs);// 排序
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < mySs.length; i++) {
			result.add(mySs[i].s);
		}
		return result;
	}
	
	public static void main(String[] args) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("transaction_id", "4000532001201604225095569126");
		params.put("nonce_str", "K5UDG9sH4pFaAlvqmLg0FUd8RptFHRKC");
		params.put("bank_type", "CFT");
		params.put("openid", "owEBIszi3cSzyCNSGHT9cCfyQ2Zg");
		params.put("sign", "147943C8D2FEDDD9E444F0724C76A7B6");
		params.put("fee_type", "CNY");
		params.put("mch_id", WxConstants.MCHID);
		params.put("cash_fee", "1");
		params.put("out_trade_no", "2016042216120575719");
		params.put("appid", WxConstants.APPID);
		params.put("total_fee", "1");
		params.put("trade_type", "JSAPI");
		params.put("result_code", "SUCCESS");
		params.put("attach", "标记参数");
		params.put("time_end", "20160422162017");
		params.put("is_subscribe", "Y");
		params.put("return_code", "SUCCESS");
		params.remove("sign");
		String sign = SignUtil.getSign(params);
		System.out.println(sign);
	}
	
}

class MyString implements Comparable<MyString> {
	public String s;// 包装String

	public MyString(String s) {
		this.s = s;
	}

	public int compareTo(MyString o) {
		if (o == null || o.s == null) {
			return 1;
		}
		return s.compareTo(o.s);
	}
}
